﻿using Microsoft.Extensions.Configuration;
using SqlSugar;
using System.Xml;
using Volo.Abp.Modularity;
using Volo.Abp;
using Volo.Abp.MultiTenancy;
using SqlSugar.IOC;
using Microsoft.Extensions.DependencyInjection;
using Flies.SQLSugarCore.Tool;
using System.Configuration;
using Volo.Abp.Data;
using Files.Domain;

[DependsOn(typeof(AbpMultiTenancyModule),
            typeof(DomainModule),
    typeof(AbpDataModule))] // 多租户依赖

public class SqlSugarModule : AbpModule
{

    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        var configuration = context.Services.GetConfiguration();
        // 获取数据库配置
        var dbConfigs = configuration.GetSection("ConnectionConfigs").Get<List<IocConfig>>();

        // 注册SqlSugar服务
        context.Services.AddSqlSugar(dbConfigs);

    }


    public override void OnApplicationInitialization(ApplicationInitializationContext context)
    {
        // 初始化数据库表结构
        var sqlSugar = context.ServiceProvider.GetService<ISqlSugarClient>();
        // 扫描所有程序集中的实体类并创建表

        var entityTypes = ModuleHelper.GetEntityTypesFromAllModules();
        foreach (var entityType in entityTypes)
        {
            if (entityType.IsAbstract || entityType.IsInterface)
                continue;

            try
            {
                sqlSugar.DbMaintenance.CreateDatabase();
                sqlSugar?.CodeFirst.InitTables(entityType);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Init table failed for type {entityType.FullName}: {ex.Message}");
            }
        }
    }
}